package com.korion.android.devicedemon

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.korion.android.devicedemon.core.CheckUtils
import com.korion.android.devicedemon.base.LocalSettings
import com.korion.android.devicedemon.core.SmsUtils

class SmsTestActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        private const val TAG = "SmsTest"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sms_test)

        findViewById<EditText>(R.id.edt_phone).setText("10086")
        findViewById<EditText>(R.id.edt_message).setText("10086")

        LocalSettings.getString(LocalSettings.KEY_REMOTE_PHONE)?.run {
            findViewById<EditText>(R.id.edt_remotePhone)?.setText(this)
        }
    }

    override fun onClick(view: View) {
        when(view.id) {
            R.id.btn_readSms -> {
                if (SmsUtils.checkSmsPermission(this, SmsUtils.SMS_READ_PERMISSION_CODE, true)) {
                    SmsUtils.readSms(this)
                }
            }
            R.id.btn_sendSMS -> {
                if (SmsUtils.checkSmsPermission(this, SmsUtils.SMS_SEND_PERMISSION_CODE, true)) {
                    sendSms(this)
                }
            }
            R.id.btn_save -> {
                val phone = findViewById<EditText>(R.id.edt_remotePhone).text.toString().trim()
                if (!phone.isNullOrEmpty()) {
                    val checked = CheckUtils.checkPhoneNumber(phone)
                    if (!checked) {
                        Toast.makeText(this, "已保存，但手机号格式有误", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this, "已保存", Toast.LENGTH_SHORT).show()
                    }
                    LocalSettings.saveString(LocalSettings.KEY_REMOTE_PHONE, phone)
                }
            }
        }
    }


    private fun sendSms(context: Context) {
        val phone = findViewById<EditText>(R.id.edt_phone).text.toString().trim()
        val message = findViewById<EditText>(R.id.edt_message).text.toString().trim()
        Log.d(TAG, "send sms: phone=$phone, message:$message")
        SmsUtils.sendSms(context, phone, message)
    }
}